package com.its.us.sk.server.ws.handler;

import com.its.us.netty.server.data.User;
import com.its.us.sk.server.ws.base.BaseWebSocketHandler;
import com.its.us.sk.server.ws.config.NettyWsConfig;
import com.its.us.web.utils.JsonUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalTime;

/**
 * @Author: master
 * @Date: 2020/11/26 13:31
 * @Version: 1.0
 */
public class WebSocketHandler extends BaseWebSocketHandler {

    @Override
    protected void write(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {

        /**
         * 绑定推送给个人
         */
        User user = JsonUtil.fromJson(msg.text(), User.class);
        if (null != user.getType() && "single".equals(user.getType())) {
            if (!NettyWsConfig.getUserChannelMap().containsKey(user.getId())) {
                NettyWsConfig.getUserChannelMap().put(user.getId(), ctx.channel());
            }
        }
        // 判断
        if (user.getType() == null && null != user.getSendTo()) {
            NettyWsConfig.getUserChannelMap().forEach((s, ch) -> {
                if (user.getSendTo().equals(s)) {
                    ch.writeAndFlush(new TextWebSocketFrame("客户[" + user.getId() + "]发送内容：\n" + user.getMsg() + "\n时间：" + LocalTime.now()));
                }
                if (user.getId().equals(s)) {
                    ch.writeAndFlush(new TextWebSocketFrame("自己[" + user.getId() + "]发送内容：\n" + user.getMsg() + "\n时间：" + LocalTime.now()));
                }
            });
        }

        /**
         * 推送所有逻辑
         */
        /*Channel inComing = ctx.channel();
        NettyWsConfig.getChannelGroup().forEach(ch -> {
            if (ch != inComing) {
                //ch.writeAndFlush(new TextWebSocketFrame("客户[" + inComing.remoteAddress() + "]：" + msg.text() + " 时间：" + LocalTime.now()));
                ws(ch,"客户[" + inComing.remoteAddress() + "]：" + msg.text() + " 时间：" + LocalTime.now());
            } else {
                ws(ch,"自己[" + inComing.remoteAddress() + "]：" + msg.text() + " 时间：" + LocalTime.now());
            }
        });*/
    }
}
